using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace MaterialUI
{
	[ExecuteInEditMode]
	[AddComponentMenu("MaterialUI/Sprite Swapper", 50)]
	public class SpriteSwapper : UIBehaviour
	{
		[SerializeField]
		private Image m_TargetImage;

		[SerializeField]
		private MaterialUIScaler m_RootScaler;

		[SerializeField]
		private Sprite m_Sprite1X;

		[SerializeField]
		private Sprite m_Sprite2X;

		[SerializeField]
		private Sprite m_Sprite4X;

		private Sprite m_LastSprite1X;

		private Sprite m_LastSprite2X;

		private Sprite m_LastSprite4X;

		public Image targetImage
		{
			get
			{
				return m_TargetImage;
			}
			set
			{
				m_TargetImage = value;
				RefreshSprite();
			}
		}

		public MaterialUIScaler rootScaler
		{
			get
			{
				if (m_RootScaler == null)
				{
					m_RootScaler = MaterialUIScaler.GetParentScaler(base.transform);
				}
				return m_RootScaler;
			}
		}

		public Sprite sprite1X
		{
			get
			{
				return m_Sprite1X;
			}
			set
			{
				m_Sprite1X = value;
				RefreshSprite();
			}
		}

		public Sprite sprite2X
		{
			get
			{
				return m_Sprite2X;
			}
			set
			{
				m_Sprite2X = value;
				RefreshSprite();
			}
		}

		public Sprite sprite4X
		{
			get
			{
				return m_Sprite4X;
			}
			set
			{
				m_Sprite4X = value;
				RefreshSprite();
			}
		}

		protected override void OnEnable()
		{
			if (!targetImage)
			{
				targetImage = base.gameObject.GetComponent<Image>();
			}
			RefreshSprite();
		}

		protected override void Start()
		{
			if (!(this.rootScaler == null))
			{
				MaterialUIScaler rootScaler = this.rootScaler;
				rootScaler.OnScaleFactorChange = (MaterialUIScaler.ScaleFactorChangeEvent)Delegate.Combine(rootScaler.OnScaleFactorChange, new MaterialUIScaler.ScaleFactorChangeEvent(SwapSprite));
				RefreshSprite();
			}
		}

		public void RefreshSprite()
		{
			if (!(rootScaler == null))
			{
				SwapSprite(rootScaler.scaler.scaleFactor);
			}
		}

		private void SwapSprite(float scaleFactor)
		{
			if ((bool)targetImage)
			{
				if (scaleFactor > 2f && (bool)sprite4X)
				{
					targetImage.sprite = sprite4X;
				}
				else if (scaleFactor > 1f && (bool)sprite2X)
				{
					targetImage.sprite = sprite2X;
				}
				else
				{
					targetImage.sprite = sprite1X;
				}
			}
		}
	}
}
